package com.ltkj.baseplatform.service.impl;

import com.ltkj.baseplatform.domain.SerAgreement;
import com.ltkj.baseplatform.domain.SerGameData;
import com.ltkj.baseplatform.domain.SerGameMember;
import com.ltkj.baseplatform.domain.bo.SerGameMemberQueryBo;
import com.ltkj.baseplatform.domain.vo.SerGameDataVo;
import com.ltkj.baseplatform.domain.vo.SerGameMemberVo;
import com.ltkj.baseplatform.mapper.*;
import com.ltkj.baseplatform.service.ISerGameDataService;
import com.ltkj.common.core.domain.R;
import com.ltkj.common.core.exception.ServiceException;
import com.ltkj.common.core.utils.DateUtils;
import com.ltkj.common.core.utils.StringUtils;
import com.ltkj.common.core.web.domain.AjaxResult;
import com.ltkj.common.security.utils.SecurityUtils;
import com.ltkj.system.api.RemoteOrderService;
import com.ltkj.system.api.domain.AppletOrderDetailVo;
import com.ltkj.system.api.domain.OrderDetailQueryDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 赛事Service业务层处理
 * 
 * @author ruoyi
 * @date 2023-09-13
 */
@Service
public class SerGameDataServiceImpl implements ISerGameDataService 
{
    @Autowired
    private SerGameDataMapper serGameDataMapper;

    @Autowired
    private SerGameDataBizMapper serGameDataBizMapper;

    @Autowired
    private SerGameMemberBizMapper serGameMemberBizMapper;

    @Autowired
    private SerGameMemberMapper serGameMemberMapper;

    @Autowired
    private SerAgreementMapper serAgreementMapper;

    @Autowired
    private RemoteOrderService remoteOrderService;

    /**
     * 查询赛事
     * 
     * @param id 赛事主键
     * @return 赛事
     */
    @Override
    public SerGameData selectSerGameDataById(Long id)
    {
        return serGameDataMapper.selectSerGameDataById(id);
    }

    /**
     * 查询赛事列表
     * 
     * @param serGameData 赛事
     * @return 赛事
     */
    @Override
    public List<SerGameData> selectSerGameDataList(SerGameData serGameData)
    {
        return serGameDataMapper.selectSerGameDataList(serGameData);
    }

    /**
     * 新增赛事
     * 
     * @param serGameData 赛事
     * @return 结果
     */
    @Override
    public int insertSerGameData(SerGameData serGameData)
    {
        Date nowDate = DateUtils.getNowDate();
        validateBeforeSave(serGameData,nowDate);
        serGameData.setCreateTime(nowDate);
        serGameData.setCreateBy(SecurityUtils.getLoginUser().getUsername());
        return serGameDataMapper.insertSerGameData(serGameData);
    }
    /**
     * 修改赛事
     * 
     * @param serGameData 赛事
     * @return 结果
     */
    @Override
    public int updateSerGameData(SerGameData serGameData)
    {
        Date nowDate = DateUtils.getNowDate();
        validateBeforeUpdate(serGameData,nowDate);
        serGameData.setUpdateTime(nowDate);
        serGameData.setUpdateBy(SecurityUtils.getLoginUser().getUsername());
        return serGameDataMapper.updateSerGameData(serGameData);
    }

    /**
     * 批量删除赛事
     * 
     * @param ids 需要删除的赛事主键
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteSerGameDataByIds(Long[] ids)
    {
        int i = serGameDataBizMapper.deleteSerGameDataByIds(ids);
        if(i > 0){
            //同步删除赛事成员表
            List<SerGameMemberVo> list = serGameMemberBizMapper.selectSerGameMemberListByIds(ids);
            if(list.size() > 0){
                List<Long> idList = list.stream().map(item -> item.getId()).collect(Collectors.toList());
                Long[] array = new Long[idList.size()];
                serGameMemberBizMapper.deleteSerGameMemberByIds(idList.toArray(array));
            }
        }
        return i;
    }

    /**
     * 删除赛事信息
     * 
     * @param id 赛事主键
     * @return 结果
     */
    @Override
    public int deleteSerGameDataById(Long id)
    {
        return serGameDataMapper.deleteSerGameDataById(id);
    }

    @Override
    public SerGameDataVo selectSerGameDataVoById(Long id) {
        SerGameDataVo serGameDataVo = serGameDataBizMapper.selectSerGameDataById(id);
        //查询协议
        SerAgreement serAgreement = serAgreementMapper.selectSerAgreementById(serGameDataVo.getGameAgreementId());
        serGameDataVo.setAgreementName(serAgreement.getAgreementName());
        serGameDataVo.setContent(serAgreement.getContent());
        return serGameDataVo;
    }

    @Override
    public SerGameDataVo selectSerGameDetailById(Long id) {
        SerGameDataVo serGameDataVo = serGameDataBizMapper.selectSerGameDataById(id);
        SerGameMemberQueryBo serGameMemberQueryBo = new SerGameMemberQueryBo();
        serGameMemberQueryBo.setGameId(serGameDataVo.getId());
        serGameMemberQueryBo.setUserId(SecurityUtils.getLoginUser().getUserid());
        List<SerGameMemberVo> members = serGameMemberBizMapper.selectSerGameMemberList(serGameMemberQueryBo);
        serGameDataVo.setMemberList(members);
        //查询订单详情获取状态和支付时间
        OrderDetailQueryDTO queryDTO = new OrderDetailQueryDTO();
        queryDTO.setTicketId(serGameDataVo.getId());
        queryDTO.setTicketType("5");
        queryDTO.setUserId(SecurityUtils.getLoginUser().getUserid());
        R<List<AppletOrderDetailVo>> result = remoteOrderService.queryOrderDetail(queryDTO);
        if (StringUtils.isNull(result) || StringUtils.isNull(result.getData())){
            throw new ServiceException("查询报名状态失败！");
        }

        AppletOrderDetailVo appletOrderDetailVo = result.getData().get(0);

        if(appletOrderDetailVo != null){
            serGameDataVo.setResidueTimeNum(appletOrderDetailVo.getResidueTimeNum());
            serGameDataVo.setTicketStatus(appletOrderDetailVo.getTicketStatus());
        }
        return serGameDataVo;
    }

    @Override
    public List<SerGameDataVo> selectSerGameDataVoList(SerGameData serGameData) {
        //serGameData.setExpireTime(DateUtils.getNowDate());
        return serGameDataBizMapper.selectSerGameDataList(serGameData);
    }

    //小程序使用的查询赛事列表
    @Override
    public List<SerGameDataVo> selectSerGameDataAppletList(SerGameData serGameData) {
        List<SerGameDataVo> serGameDataVos = serGameDataBizMapper.selectSerGameDataList(serGameData);
        if(serGameDataVos == null || serGameDataVos.size() == 0){
            return serGameDataVos;
        }
        List<Long> gameIdList = serGameDataVos.stream().map(item -> item.getId()).collect(Collectors.toList());

        //查询已报名的队伍列表
        SerGameMemberQueryBo bo = new SerGameMemberQueryBo();
        bo.setGameIdList(gameIdList);
        bo.setIsCaptain("1");
        //bo.setStatus("1");//已报名状态,目前不使用，支付后才是报名成功
        List<SerGameMemberVo> memberList = serGameMemberBizMapper.selectSerGameMemberList(bo);
        if(memberList == null || memberList.size() == 0){
            return serGameDataVos;
        }
        //查询订单详情获取状态和支付时间
        OrderDetailQueryDTO queryDTO = new OrderDetailQueryDTO();
        queryDTO.setTicketIds(gameIdList);
        queryDTO.setTicketType("5");
        queryDTO.setTicketStatus("2");
        R<List<AppletOrderDetailVo>> result = remoteOrderService.queryOrderDetail(queryDTO);
        if (StringUtils.isNull(result) || StringUtils.isNull(result.getData())){
            throw new ServiceException("查询报名状态失败！");
        }
        //根据赛事id分组，在集合中的数据都是已支付的
        Map<Long,Set<Long>> gameMap = new HashMap<>();
        for (AppletOrderDetailVo datum : result.getData()) {
            Long key = datum.getTicketId();
            if(gameMap.containsKey(key)){
                //如果map中存在以此id作为的key,将数据元素存放当前key的list集合中
                gameMap.get(key).add(datum.getUserId());
            }else{
                Set<Long> userIdSet = new HashSet<>();
                userIdSet.add(datum.getUserId());
                gameMap.put(key,userIdSet);
            }
        }
        //根据赛事id分组
        Map<Long, List<SerGameMemberVo>> groupMap = new HashMap<>();
        if(gameMap.size() != 0){
            for (SerGameMemberVo serGameMemberVo : memberList) {
                Long gameId = serGameMemberVo.getGameId();
                if(gameMap.get(gameId) != null && gameMap.get(gameId).contains(serGameMemberVo.getUserId())){
                    if(groupMap.containsKey(gameId)){
                        //如果map中存在以此id作为的key,将数据元素存放当前key的list集合中
                        groupMap.get(gameId).add(serGameMemberVo);
                    }else{
                        List<SerGameMemberVo> serGameMemberVoList = new ArrayList<>();
                        serGameMemberVoList.add(serGameMemberVo);
                        groupMap.put(gameId,serGameMemberVoList);
                    }
                }
            }
        }
        //设置已报名成员
        for (SerGameDataVo serGameDataVo : serGameDataVos) {
            serGameDataVo.setMemberList(groupMap.get(serGameDataVo.getId()));
        }
        return serGameDataVos;
    }

    /**
     * 查询我的赛事
     * @return
     */
    @Override
    public List<SerGameDataVo> selectMySerGameDataList() {
        Long userId = SecurityUtils.getLoginUser().getUserid();
    /*    SerGameMember serGameMember = new SerGameMember();
        serGameMember.setUserId(userId);
        serGameMember.setIsCaptain("1");
        List<SerGameMember> members = serGameMemberMapper.selectSerGameMemberList(serGameMember);
        Set<Long> ids = members.stream().map(item -> item.getGameId()).collect(Collectors.toSet());
        List<SerGameDataVo> serGameDataVos1 = serGameDataBizMapper.selectSerGameDataListByIds(ids);*/
        List<SerGameDataVo> serGameDataVos = serGameDataBizMapper.selectMySerGameDataList(userId);
        for (SerGameDataVo serGameDataVo : serGameDataVos) {
            if("1".equals(serGameDataVo.getGameStatus())){
                serGameDataVo.setGameStatus("已报名");
            }else if("2".equals(serGameDataVo.getGameStatus())){
                serGameDataVo.setGameStatus("已退费");
            }
        }
        return serGameDataVos;
    }

    @Override
    public int deleteGameMemberByUserIdAndGameId(Long userId, Long gameId) {
        return serGameMemberBizMapper.deleteGameMemberByUserIdAndGameId(userId,gameId);
    }

    //添加前校验
    private void validateBeforeSave(SerGameData serGameData,Date nowDate) {
        /*if (serGameData.getExpireTime() == null) {
            throw new ServiceException("请输入赛事截止日期！");
        }
        if (DateUtils.parseDateToStr("yyyy-MM-dd",serGameData.getExpireTime()).compareTo(DateUtils.parseDateToStr("yyyy-MM-dd",nowDate)) < 0) {
            throw new ServiceException("赛事截止日期不能小于当前日期！");
        }*/
        int i = serGameDataBizMapper.isRepeat(serGameData);
        if(i > 0){
            throw new ServiceException("赛事名称重复！");
        }
    }
    //修改前校验
    private void validateBeforeUpdate(SerGameData serGameData,Date nowDate) {
        /*if (serGameData.getExpireTime() == null) {
            throw new ServiceException("请输入赛事截止日期！");
        }
        if (DateUtils.parseDateToStr("yyyy-MM-dd",serGameData.getExpireTime()).compareTo(DateUtils.parseDateToStr("yyyy-MM-dd",nowDate)) < 0) {
            throw new ServiceException("赛事截止日期不能小于当前日期！");
        }*/
        int i = serGameDataBizMapper.isRepeatExcludeSelf(serGameData);
        if(i > 0){
            throw new ServiceException("赛事名称重复！");
        }
    }
}
